/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet.chat;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Room;
import model.Rooms;
import model.User;
import model.Users;
import model.db.UsersDB;
import model.panel.RoomCategory;
import model.panel.RoomPanel;

/**
 *
 * @author user
 */
public class RoomServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();

        // Get Servlet Context
        ServletContext sc = getServletContext();

        Rooms rooms = new Rooms();

        // Add object to application session
        sc.setAttribute("rooms", rooms);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = (String) request.getSession().getAttribute("username");
        int userId = (Integer) request.getSession().getAttribute("id");

        Rooms rooms = (Rooms) getServletContext().getAttribute("rooms");
        RoomPanel roomPanel = new RoomPanel(-1, "panel", rooms);

        String action = request.getParameter("action");
        String targetUser = request.getParameter("targetUser");
        String value = request.getParameter("value");
        String strRoomId = request.getParameter("roomId");
        int roomId = -1;
        if (strRoomId != null && strRoomId.length() > 0) {
            roomId = Integer.parseInt(request.getParameter("roomId"));
        }

        String strOut = "[]";
        Gson gson = new Gson();

        if (action.equals("listRoom")) {
            strOut = gson.toJson(roomPanel);
            System.out.println(strOut);

        } else if (action.equals("listUser")) {
            Room room = rooms.find(roomId);
            strOut = gson.toJson(room.joinUsers);
            System.out.println("joinUser : " + strOut);

        } else if (action.equals("create")) {
            strOut = createRoom(request, roomPanel);
            System.out.println("create : " + strOut);

        } else if (action.equals("iskick")) {
            boolean result = rooms.isKickAndRemove(userId, roomId);
            strOut = gson.toJson(result);
            
        } else if (action.equals("kick")) {
            Room room = rooms.find(roomId);
            if (room.ownerId == userId) {
                room.markKickToUser(targetUser);
            }

        } else if (action.equals("ban")) {
            Room room = rooms.find(roomId);
            if (room.ownerId == userId) {
                UsersDB usersDB = new UsersDB();
                User user = usersDB.find(targetUser);
                room.addBanUsers(user);
            }
            
        } else if (action.equals("unban")) {
            Room room = rooms.find(roomId);
            if (room.ownerId == userId) {
                room.removeBanUsers(targetUser);
            }
            
        } else if (action.equals("persist")) {
            Room room = rooms.find(roomId);
            if (room.ownerId == userId) {
                room.persistance = value.equals("yes");
            }
            
        } else if (action.equals("setowner")) {
            Room room = rooms.find(roomId);
            if (room.ownerId == userId) {
                rooms.setOwner(targetUser, roomId);
            }
            
        }

        try {
            out.println(strOut);
        } finally {
            out.close();
        }
    }

    private String createRoom(HttpServletRequest request, RoomPanel roomPanel) {
        int userId = (Integer) request.getSession().getAttribute("id");
        String roomName = request.getParameter("name");
        System.out.println("roomName : " + roomName);
        String categ = request.getParameter("categ");
        Gson gson = new Gson();

        // Get Rooms
        Rooms rooms = (Rooms) getServletContext().getAttribute("rooms");
        // Check avail name
        if (rooms.find(roomName) != null) {
            return "{error:\"Room's name is exist.\"}";
        }

        // Check avail category
        if (categ == null || categ.length() == 0) {
            return "{error:\"Category not found.\"}";
        }

        RoomCategory rm = roomPanel.find(categ);
        System.out.println("Categ : " + categ);
        if (rm == null) {
            return "{error:\"Category not found.\"}";
        }

        // Check max room
        if (!canCreateRoom(request)) {
            return "{error:\"Number room is max.\"}";
        }

        // Create
        Room newRoom = new Room(rm.rooms.size(), roomName, rm.id, userId, false);
        rooms.add(newRoom);

        // Add held
        addHeld(request);

        return gson.toJson(newRoom);
    }

    public boolean canCreateRoom(HttpServletRequest request) {
        int userId = (Integer) request.getSession().getAttribute("id");
        Users loginUsers = (Users) getServletContext().getAttribute("loginUsers");

        UsersDB udb = new UsersDB();
        User user = udb.find(userId);

        if (user != null) {
            return loginUsers.find(userId).heldRoom < user.maxNumberRoom;
        }

        return false;
    }

    private void addHeld(HttpServletRequest request) {
        int userId = (Integer) request.getSession().getAttribute("id");
        Users loginUsers = (Users) getServletContext().getAttribute("loginUsers");
        loginUsers.find(userId).heldRoom++;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
